import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { User, CreateUserRequest, UpdateUserRequest } from '../types/user'
import { userApi } from '../api/userApi'
import { ElMessage, ElMessageBox } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  // 状态
  const users = ref<User[]>([])
  const loading = ref(false)
  const saving = ref(false)

  // Getters
  const userCount = () => users.value.length
  const getUserById = (id: number) => users.value.find(user => user.id === id)

  // Actions
  const loadUsers = async () => {
    loading.value = true
    try {
      users.value = await userApi.getUsers()
    } catch (error) {
      ElMessage.error('加载用户列表失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  const createUser = async (userData: CreateUserRequest) => {
    saving.value = true
    try {
      const newUser = await userApi.createUser(userData)
      users.value.push(newUser)
      ElMessage.success('用户添加成功')
      return newUser
    } catch (error) {
      ElMessage.error('添加用户失败')
      throw error
    } finally {
      saving.value = false
    }
  }

  const updateUser = async (id: number, userData: UpdateUserRequest) => {
    saving.value = true
    try {
      const updatedUser = await userApi.updateUser(id, userData)
      const index = users.value.findIndex(user => user.id === id)
      if (index !== -1) {
        users.value[index] = { ...users.value[index], ...updatedUser }
      }
      ElMessage.success('用户更新成功')
      return updatedUser
    } catch (error) {
      ElMessage.error('更新用户失败')
      throw error
    } finally {
      saving.value = false
    }
  }

  const deleteUser = async (id: number) => {
    try {
      await ElMessageBox.confirm('确定要删除这个用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      await userApi.deleteUser(id)
      users.value = users.value.filter(user => user.id !== id)
      ElMessage.success('用户删除成功')
    } catch (error) {
      // 用户取消删除
      throw error
    }
  }

  return {
    // 状态
    users,
    loading,
    saving,
    
    // Getters
    userCount,
    getUserById,
    
    // Actions
    loadUsers,
    createUser,
    updateUser,
    deleteUser
  }
})
